﻿
using System.IO.Ports;
using System.Threading;


namespace libcontrol
{
    public delegate void EventHandler_Comm(byte[] readBuffer);

    class SerialPortHelper
    {
        public event EventHandler_Comm DataReceived;

        public SerialPort serialPort;
        Thread thread;
        volatile bool _keepReading;

        public SerialPortHelper()
        {
            serialPort = new SerialPort();
            thread = null;
            _keepReading = false;
        }

        public bool IsOpen
        {
            get
            {
                return serialPort.IsOpen;
            }
        }

        private void StartReading()
        {
            if (!_keepReading)
            {
                _keepReading = true;
                thread = new Thread(new ThreadStart(ReadPort));
                thread.Start();
            }
        }

        private void StopReading()
        {
            _keepReading = false;
            if (!_keepReading)
            {
                _keepReading = false;
                //thread.Join();
                thread = null;
            }
        }

        private void ReadPort()
        {
            while (_keepReading)
            {
                if (serialPort.IsOpen)
                {
                    int count=-1;
                    Thread.Sleep(30);
                    try
                    {
                        count = serialPort.BytesToRead;
                    }
                    catch 
                    {}                    
                    if (count > 0)
                    {
                        byte[] readBuffer = new byte[count];
                        try
                        {
                         //   Application.DoEvents();
                            serialPort.Read(readBuffer, 0, count);
                            if (DataReceived != null)
                            {
                                DataReceived(readBuffer);
                            }
                            Thread.Sleep(50);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }

        public bool Open()
        {
            bool ret = true;
            try
            {
                //Close();
                serialPort.Open();
            }
            catch
            {
                return false;
            }

            if (serialPort.IsOpen)
            {
                StartReading();
            }
            else
            {
                ret = false;//MessageBox.Show("串口打开失败！");
            }
            return ret;
        }

        public void Close()
        {
            StopReading();
            serialPort.Close();
        }

        public void WritePort(byte[] send, int offSet, int count)
        {
            if (IsOpen)
            {
                serialPort.Write(send, offSet, count);
            }
        }

        public void WriteFile(string txt)
        {
            if (IsOpen)
            {
                serialPort.WriteLine(txt);
            }
        }
        #region
        ////字符长度的理解
        //    string s = "我是一个2兵";
        //     int len = s.Length;//6个字符  
        //     byte[] sarr = System.Text.Encoding.Default.GetBytes(s);
        //     len = sarr.Length;//11个字节  

        //     //10进制转字符串，也没有意义，要转成对应的ascii码
        //    int t1 = 81;
        //     string s1 = t1.ToString();
        //     //这个10进制转对应ASCII字符才有意义。
        //    s1 = ((char)t1).ToString();

        //    //16进制转字符串:这个没有意义。就是tostring了。
        //    int intAB = 0x16; 
        //     s1 = intAB.ToString();
        //     //16进制转对应ASCII字符:
        //     byte babb = 0x45;
        //     string ass = ((char)babb).ToString();

        //    //ASCII字符串转10进制数
        //    string tr = "2Ab刘";
        //     string d ="";
        //     for (int i = 0; i < tr.Length; i++)
        //     {
        //         int ii = (int)Convert.ToChar(tr.Substring(i, 1));
        //         d = d +" "+ ii.ToString();
        //     }

        //    //ASCII字符串转16进制数
        //    string s2 = "2Ab刘";
        //     byte[] ba = System.Text.ASCIIEncoding.Default.GetBytes(s2);
        //     StringBuilder sb = new StringBuilder();
        //     foreach (byte b in ba)
        //     {
        //         sb.Append(b.ToString("x") + " ");
        //     }

        //    //16进制数转10进制
        //    int intA = 0x16;//定义的时候是必须带0x的  
        //     string strA = "16";//字符串可以不带  
        //     int intA1 = Convert.ToInt32(intA);
        //     int intA2 = Convert.ToInt32(strA, 16);

        //    //10进制转16进制
        //    strA = Convert.ToString(intA2, 16);


        //    //10进制转2进制，16进制类似
        //    int int10 = 10;
        //     string str2 = Convert.ToString(int10,2);

        //    //2进制转10进制
        //    int10 = Convert.ToInt32(str2,2);

        #endregion
    }
}
